package com.example.dao.imp;

import com.example.domain.Users;
import com.example.dao.UserDao;
import com.example.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserDaoImp implements UserDao {
    @Override
    public List<Users> searchUsersByUsername(String username) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectList("com.example.dao.UserDao.searchUsersByUsername", username);
        }
    }

    @Override
    public Users getUserByUsernamePasswordAndRole(String username, String password, Integer role) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectOne("com.example.dao.UserDao.getUserByUsernamePasswordAndRole", new Users(username, password, role));
        }
    }

    @Override
    public void addUser(Users user) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            sqlSession.insert("com.example.dao.UserDao.addUser", user);
            sqlSession.commit();
        }
    }

    @Override
    public void updateUser(Users user) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            sqlSession.update("com.example.dao.UserDao.updateUser", user);
            sqlSession.commit();
        }
    }

    @Override
    public void deleteUser(Integer id) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            sqlSession.delete("com.example.dao.UserDao.deleteUser", id);
            sqlSession.commit();
        }
    }

    @Override
    public List<Users> getAllUsers() {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectList("com.example.dao.UserDao.getAllUsers");
        }
    }

    @Override
    public Users getUsersByUserId(Integer id) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectOne("com.example.dao.UserDao.getUsersByUserId", id);
        }
    }
}
